package de.pelizaeus.app;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.Toast;

import java.util.ArrayList;

import de.pelizaeus.app.other.Utils;
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.internal.CardHeader;
import it.gmariotti.cardslib.library.internal.CardThumbnail;
import it.gmariotti.cardslib.library.internal.base.BaseCard;
import it.gmariotti.cardslib.library.view.CardListView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class KalenderFragment extends BaseFragment {
    protected ScrollView mScrollView;
    protected Context context = getActivity();
    ArrayList<Card> cards = new ArrayList<Card>();

    public int getTitleResourceId() {
        return R.string.activity_name_news;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.card_list, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!Utils.isOnline(getActivity()))
        {
            Toast.makeText(getActivity(), "Es ist ein Verbindungsfehler aufgetreten!", Toast.LENGTH_SHORT).show();
            getActivity().finish();
        }
        else {
            new Parser().execute();
        }

    }


    private void initCards() {



        CardExample card;
        CardThumbnail thumb;
        thumb = new CardThumbnail(getActivity());
        thumb.setDrawableResource(R.drawable.ic_smile);
        card = new CardExample(getActivity(), "News Nr. " + 1, "Newstext");
        card.addCardThumbnail(thumb);
        cards.add(card);

        CardArrayAdapter mCardArrayAdapter = new CardArrayAdapter(getActivity(), cards);

        CardListView listView = (CardListView) getActivity().findViewById(R.id.carddemo_list);
        if (listView != null) {
            listView.setAdapter(mCardArrayAdapter);
        }
    }

    private class Parser extends AsyncTask<Void,Void,Void>
    {
        String string = "";

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            getActivity().setProgressBarIndeterminate(true);
            getActivity().setProgressBarIndeterminateVisibility(true);
        }
        @Override
        protected Void doInBackground(Void... voids) {

            String url = "http://pelizaeus.lspb.de/typo3/kalender/listen-ansicht";
            System.out.println("Fetching " + url);
            string = string + "Fetching " + url + "\n";
            try {
                Document doc = Jsoup.connect(url).get();
                Elements events = doc.select(".vevent");
                Elements date = null;
                Elements name = null;


                System.out.print("\n " + events.size() + " Termine:");
                string = string + "\n" + events.size() + " Termine:" + "\n";
                for (Element link : events) {
                    date = link.select(".dtstart");
                    name = link.select(".summary");
                    String datum = link.select("abbr").first().attr("title");
                    // String parsen
                    // Bsp: 20140623T000000
                    String jahr = datum.substring(0, 4);
                    String monat = datum.substring(4, 6);
                    String tag = datum.substring(6, 8);


                    CardExample card;
                    CardThumbnail thumb;
                    thumb = new CardThumbnail(getActivity());
                    thumb.setDrawableResource(R.drawable.ic_smile);
                    card = new CardExample(getActivity(), tag + "." + monat + "." + jahr, name.text());
                    card.addCardThumbnail(thumb);
                    cards.add(card);

                    System.out.println("Datum: " + tag + "." + monat + "." + jahr);
                    string = string + "\n" + "Datum: " + tag + "." + monat + "." + jahr;
                    System.out.print(" * " + name.text() + link.attr("rel"));
                    string = string + "\n" +  " * " + name.text() + link.attr("rel");
                }

            }
            catch (Exception e)
            {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {

                        Toast.makeText(context, "Es ist ein Verbindungsfehler aufgetreten!", Toast.LENGTH_SHORT).show();
                    }
                });
                e.printStackTrace();
                getActivity().finish();
            }
            return null;
        }

        protected void onPostExecute(Void result)
        {
            // ((TextView) getActivity().findViewById(R.id.textView)).setText(string);
            CardArrayAdapter mCardArrayAdapter = new CardArrayAdapter(getActivity(), cards);

            CardListView listView = (CardListView) getActivity().findViewById(R.id.carddemo_list);
            if (listView != null) {
                listView.setAdapter(mCardArrayAdapter);
            }
            getActivity().setProgressBarIndeterminateVisibility(false);
        }

    }

    public class CardExample extends Card {

        protected String mTitleHeader;
        protected String mTitleMain;

        public CardExample(Context context, String titleHeader, String titleMain) {
            super(context, R.layout.card_inner_kalender);
            this.mTitleHeader = titleHeader;
            this.mTitleMain = titleMain;
            init();
        }

        private void init() {

            //Create a_gebaeude CardHeader
            CardHeader header = new CardHeader(getActivity());

            //Set the header title
            header.setTitle(mTitleHeader);

            //Add a_gebaeude popup menu. This method set OverFlow button to visible
            header.setPopupMenu(R.menu.global, new CardHeader.OnClickCardHeaderPopupMenuListener() {
                @Override
                public void onMenuItemClick(BaseCard card, MenuItem item) {
                    Toast.makeText(getActivity(), "Click on card menu" + mTitleHeader + " item=" + item.getTitle(), Toast.LENGTH_SHORT).show();
                }
            });
            addCardHeader(header);

            //Add ClickListener
            setOnClickListener(new OnCardClickListener() {
                @Override
                public void onClick(Card card, View view) {
                    Toast.makeText(getContext(), "Click Listener card=" + mTitleHeader, Toast.LENGTH_SHORT).show();
                }
            });

            //Set the card inner text
            setTitle(mTitleMain);
        }

    }
}
